import json
import os


class ScoreBoard:
    def __init__(self, filepath: str):
        self.filepath = filepath
        # scores is a list of records: {"name": str, "score": int}
        self.scores = []
        self.load()

    def load(self):
        try:
            if os.path.exists(self.filepath):
                with open(self.filepath, "r", encoding="utf-8") as f:
                    data = json.load(f)
                    if isinstance(data, list):
                        # normalize old-format lists of ints to new format
                        normalized = []
                        for item in data:
                            if isinstance(item, dict) and "score" in item and "name" in item:
                                normalized.append({"name": str(item.get("name", "Player")), "score": int(item.get("score", 0))})
                            else:
                                try:
                                    normalized.append({"name": "Player", "score": int(item)})
                                except Exception:
                                    pass
                        self.scores = normalized
                    else:
                        self.scores = []
            else:
                self.scores = []
        except Exception:
            self.scores = []

    def save(self):
        try:
            with open(self.filepath, "w", encoding="utf-8") as f:
                json.dump(self.scores, f, ensure_ascii=False, indent=2)
        except Exception:
            pass

    def add_score(self, score: int, name: str = "Player"):
        try:
            rec = {"name": str(name) if name else "Player", "score": int(score)}
            self.scores.append(rec)
            # sort by score descending
            self.scores = sorted(self.scores, key=lambda r: r.get("score", 0), reverse=True)
            self.scores = self.scores[:100]
        except Exception:
            pass

    def top(self, n=10):
        return self.scores[:n]
